<template>
  <el-form ref="formRef" :model="modelData" :rules="rules" label-width="120px" class="mt-20px">
    <el-form-item label="流程标识" prop="key" class="mb-20px">
      <div class="flex items-center">
        <el-input
          class="!w-440px"
          v-model="modelData.key"
          :disabled="!!modelData.id"
          placeholder="请输入流程标识，以字母或下划线开头"
        />
        <el-tooltip
          class="item"
          :content="modelData.id ? '流程标识不可修改！' : '新建后，流程标识不可修改！'"
          effect="light"
          placement="right"
        >
          <Icon icon="ep:question-filled" class="ml-5px" />
        </el-tooltip>
      </div>
    </el-form-item>
    <el-form-item label="流程名称" prop="name" class="mb-20px">
      <div class="flex items-center">
        <el-input
          class="!w-440px"
          v-model="modelData.name"
          :disabled="!!modelData.id"
          placeholder="请输入流程名称"
        />
        <el-tooltip
          class="item"
          :content="modelData.id ? '流程名称不可修改！' : '新建后，流程名称不可修改！'"
          effect="light"
          placement="right"
        >
          <Icon icon="ep:question-filled" class="ml-5px" />
        </el-tooltip>
      </div>
    </el-form-item>
    <el-form-item label="流程分类" prop="category" class="mb-20px">
      <el-select
        class="!w-full"
        v-model="modelData.category"
        clearable
        placeholder="请选择流程分类"
      >
        <el-option
          v-for="category in categoryList"
          :key="category.code"
          :label="category.name"
          :value="category.code"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="流程图标" class="mb-20px">
      <UploadImg v-model="modelData.icon" height="64px" width="64px" />
    </el-form-item>
    <el-form-item label="流程描述" prop="description" class="mb-20px">
      <el-input v-model="modelData.description" clearable type="textarea" />
    </el-form-item>
    <el-form-item label="是否可见" prop="visible" class="mb-20px">
      <el-radio-group v-model="modelData.visible">
        <el-radio v-for="dict in common_bool_type" :key="String(dict.value)" :value="dict.value">
          {{ dict.label }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="谁可以发起" prop="startUserType" class="mb-20px">
      <el-select
        v-model="modelData.startUserType"
        placeholder="请选择谁可以发起"
        @change="handleStartUserTypeChange"
      >
        <el-option label="全员" :value="UserSelectScopeEnum.All" />
        <el-option label="指定人员" :value="UserSelectScopeEnum.Selected" />
      </el-select>
      <div
        v-if="modelData.startUserType === UserSelectScopeEnum.Selected"
        class="mt-2 flex flex-wrap gap-2"
      >
        <div
          v-for="user in selectedStartUsers"
          :key="user.staffId"
          class="bg-gray-100 h-35px rounded-3xl flex items-center pr-8px dark:color-gray-600 position-relative"
        >
          <el-avatar class="!m-5px" :size="28" v-if="user.avatar" :src="s_file_url(user.avatar)" />
          <el-avatar class="!m-5px" :size="28" v-else>
            {{ user.nickname.substring(0, 1) }}
          </el-avatar>
          {{ user.nickname }}
          <Icon
            icon="ep:close"
            class="ml-2 cursor-pointer hover:text-red-500"
            @click="handleRemoveStartUser(user)"
          />
        </div>
        <el-button type="primary" link @click="openStartUserSelect">
          <Icon icon="ep:plus" />
          选择人员
        </el-button>
      </div>
    </el-form-item>
    <el-form-item label="流程管理员" prop="manageUserIds" class="mb-20px">
      <div class="flex flex-wrap gap-2">
        <div
          v-for="user in selectedManageUsers"
          :key="user.staffId"
          class="bg-gray-100 h-35px rounded-3xl flex items-center pr-8px dark:color-gray-600 position-relative"
        >
          <el-avatar class="!m-5px" :size="28" v-if="user.avatar" :src="s_file_url(user.avatar)" />
          <el-avatar class="!m-5px" :size="28" v-else>
            {{ user.nickname.substring(0, 1) }}
          </el-avatar>
          {{ user.nickname }}
          <Icon
            icon="ep:close"
            class="ml-2 cursor-pointer hover:text-red-500"
            @click="handleRemoveManageUser(user)"
          />
        </div>
        <el-button type="primary" link @click="openManageUserSelect">
          <Icon icon="ep:plus" />
          选择人员
        </el-button>
      </div>
    </el-form-item>
  </el-form>
  <!-- 用户选择弹窗 -->
  <UserSelectForm ref="userSelectFormRef" @confirm="handleUserSelectConfirm" />
</template>

<script setup lang="ts">
import { StaffVO } from '@/api/system/staff'
import { CategoryVO } from '@/api/bpm/category'
import UserSelectForm from '@/components/UserSelectForm/index.vue'
import { s_file_url } from '@/utils/lizard'
import { UserSelectScopeEnum } from '@/utils/constants'

defineOptions({ name: 'BpmModelBasicInfo' })

const { common_bool_type } = useBoolDict(DICT_TYPE.common_bool_type)

const props = defineProps({
  categoryList: {
    type: Array as PropType<CategoryVO[]>,
    required: true
  },
  userList: {
    type: Array as PropType<StaffVO[]>,
    required: true
  }
})

// 创建modelValue，对应vue3.3以下的defineProps(['modelValue'])与defineEmits(['update:modelValue'])
// vue3.4+开始通过defineModel即可实现以上的modelValue属性定义与更新事件声明，并且不需要执行更新事件的emit，对该数据的变更自动发送更新事件，实现双向绑定
const modelData = defineModel<any>()

const formRef = ref()
const selectedStartUsers = computed(() => {
  if (modelData.value.startUserIds?.length) {
    return props.userList.filter((user: StaffVO) =>
      modelData.value.startUserIds.includes(user.staffId)
    ) as StaffVO[]
  } else {
    return []
  }
})
const selectedManageUsers = computed(() => {
  if (modelData.value.manageUserIds?.length) {
    return props.userList.filter((user: StaffVO) =>
      modelData.value.manageUserIds.includes(user.staffId)
    ) as StaffVO[]
  } else {
    return []
  }
})
const userSelectFormRef = ref<InstanceType<typeof UserSelectForm>>()
const currentSelectType = ref<'start' | 'manage'>('start')

const rules = {
  key: [{ required: true, message: '流程标识不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '流程名称不能为空', trigger: 'blur' }],
  category: [{ required: true, message: '流程分类不能为空', trigger: 'blur' }],
  // type: [{ required: true, message: '流程类型不能为空', trigger: 'blur' }],
  visible: [{ required: true, message: '是否可见不能为空', trigger: 'blur' }],
  manageUserIds: [{ required: true, message: '流程管理员不能为空', trigger: 'blur' }]
}

const openStartUserSelect = () => {
  currentSelectType.value = 'start'
  userSelectFormRef.value?.open(0, selectedStartUsers.value)
}

const openManageUserSelect = () => {
  currentSelectType.value = 'manage'
  userSelectFormRef.value?.open(0, selectedManageUsers.value)
}

const handleUserSelectConfirm = (_, users: StaffVO[]) => {
  if (currentSelectType.value === 'start') {
    modelData.value.startUserIds = users.map((u) => u.staffId)
  } else {
    modelData.value.manageUserIds = users.map((u) => u.staffId)
  }
}

const handleStartUserTypeChange = (value: number) => {
  if (value === UserSelectScopeEnum.All) {
    modelData.value = { ...modelData.value, startUserIds: [] }
  }
}

const handleRemoveStartUser = (user: StaffVO) => {
  modelData.value.startUserIds = modelData.value.startUserIds.filter((id: string) => id !== user.staffId)
}

const handleRemoveManageUser = (user: StaffVO) => {
  modelData.value.manageUserIds = modelData.value.manageUserIds.filter((id: string) => id !== user.staffId)
}

/** 表单校验 */
const validate = async () => {
  await formRef.value?.validate()
}

defineExpose({
  validate
})
</script>

<style scoped lang="scss">
.bg-gray-100 {
  background-color: #f5f7fa;
  transition: all 0.3s;

  &:hover {
    background-color: #e6e8eb;
  }

  .ep-close {
    font-size: 14px;
    color: #909399;
    transition: color 0.3s;

    &:hover {
      color: #f56c6c;
    }
  }
}
</style>
